'use strict';
const db = uniCloud.database()
const usersCollection = db.collection('users')

exports.main = async (event, context) => {
	const { username, password } = event
	
	// 验证参数
	if (!username || !password) {
		return {
			code: -1,
			msg: '参数不完整'
		}
	}
	
	// 验证账号长度
	if (username.length < 4) {
		return {
			code: -1,
			msg: '账号长度不能少于4位'
		}
	}
	
	// 验证密码长度
	if (password.length < 6) {
		return {
			code: -1,
			msg: '密码长度不能少于6位'
		}
	}
	
	try {
		// 检查账号是否已存在
		const user = await usersCollection.where({
			username: username
		}).get()
		
		if (user.data.length > 0) {
			return {
				code: -1,
				msg: '该账号已存在'
			}
		}
		
		// 创建用户
		const userData = {
			username,
			password: password, // 实际应用中应该加密存储
			nickname: username,
			avatar: 'https://example.com/default-avatar.png', // 默认头像
			createTime: Date.now(),
			updateTime: Date.now()
		}
		
		const result = await usersCollection.add(userData)
		
		// 返回用户信息（不包含密码）
		const { password: _, ...userInfo } = userData
		userInfo._id = result.id
		
		return {
			code: 0,
			msg: '注册成功',
			data: userInfo
		}
	} catch (e) {
		return {
			code: -1,
			msg: '注册失败',
			error: e
		}
	}
}; 